package be.dch.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

import be.dch.Config;
import be.dch.objectprops.ObjectPropertiesStore;
import be.dch.objectprops.impl.ObjectPropertiesStoreImpl;

public final class ConfigUtils {

    private static final Logger LOG = Logger.getLogger(ConfigUtils.class);

    private ConfigUtils() {
	// Utility class no constructor needed.
    }

    private static final String DEFAULT_CONFIG = "/config.xml";
    private static String configlocation = ConfigUtils.DEFAULT_CONFIG;

    public static void persistConfig() {
	try {
	    final FileWriter fileWriter = new FileWriter(ConfigUtils.getConfigLocation());
	    final ObjectPropertiesStore store = new ObjectPropertiesStoreImpl();
	    store.writeObject(Config.getInstance());
	    final Properties properties = store.getDatabase();
	    properties.store(fileWriter, "My application preferences");
	} catch (final IOException e) {
	    ConfigUtils.LOG.warn(e.getMessage());
	}

    }

    public static void loadConfig() {
	final ObjectPropertiesStore store = new ObjectPropertiesStoreImpl();
	try {
	    store.getDatabase().load(new FileInputStream(new File(ConfigUtils.getConfigLocation())));
	} catch (final FileNotFoundException e) {
	    ConfigUtils.LOG.warn(e.getMessage());
	} catch (final IOException e) {
	    ConfigUtils.LOG.warn(e.getMessage());
	}
	final Config config = (Config) store.readObject(Config.class);
	Config.setConfig(config);
    }

    protected static String getConfigLocation() {
	return ConfigUtils.configlocation;
    }

    /**
     * 
     * @param location
     */
    public static void setConfigLocation(final String location) {
	ConfigUtils.configlocation = location;
    }
}
